var app = getApp();
var WxParse = require('../../lib/wxParse/wxParse.js');
var util = require('../../utils/util.js');
var api = require('../../config/api.js');
Page({
    data: {
        // 要获取的指定商品的ID
        id: 0,
        // 设备是否为苹果X
        isIphoneX: 0,
        // 商品信息
        goods: {},
        // 轮播图信息
        gallery: [],
        // 各个规格对应得商品信息
        productList: [],
        // 购物车商品数量
        cartGoodsCount: 0,
        checkedSpecPrice: 0,
        // 商品起始数量
        number: 1,
        checkedSpecText: '',
        tmpSpecText: '请选择规格和数量',
        // 控制规格和数量选择的弹出框
        openAttr: false,
        soldout: false,
        // 控制商品数量步进器的加号按钮是否可用
        disabled: '',
        userId: 0,
        priceChecked: false,
        goodsNumber: 0,
        // 加载动画
        loading: 0,
        current: 0,
        showShareDialog: 0,
        // 用户信息
        userInfo: {},
        // 轮播图自动播放
        autoplay: true,
        // 服务信息弹出框
        openServe: false,
        // 规格是否选择完整
        skuPriceVisible: false,
        // 选中商品规格的信息
        checkedSkuProductInfo: {},
        // 选中商品规格名称
        checkedSkuProductName: '',
        // 单人购买提示
        BuyRemindShow:false,
        // 推荐的评论内容
        comment:{},
        // 该商品的全部评论数量
        commentNum:0
    },
    // 取消单人购买提示
    BuyRemindClose() {
        this.setData({
            BuyRemindShow: false
        });
    },
    // 确认取消单人购买须知
    BuyRemind() {
        this.setData({
            BuyRemindShow: false
        });
    },
    // 进入界面获取传入改界面的id值
    onLoad: function (options) {
        let id = 0;
        var scene = decodeURIComponent(options.scene);
        if (scene != 'undefined') {
            id = scene;
        } else {
            id = options.id;
        }
        this.setData({
            id: id, // 这个是商品id
            valueId: id,
        });
        // 获取设备信息
        let phone = wx.getStorageSync('isIphoneX')
        if (phone) {
            this.setData({
                isIphoneX: 1
            })
        }
    },
    // 进入该界面加载请求获取数据
    onShow: function () {
        let userInfo = wx.getStorageSync('userInfo');
        let info = wx.getSystemInfoSync();
        let sysHeight = info.windowHeight - 100;
        let userId = userInfo.id;
        if (userId > 0) {
            this.setData({
                userId: userId,
                userInfo: userInfo,
            });
        }
        this.setData({
            priceChecked: false,
            sysHeight: sysHeight
        })
        this.getGoodsInfo();
        this.getCartCount();
        this.getComment();
    },
    // 跳转评论页
    toEvaluate: function () {
        let id=this.data.id;
        wx.navigateTo({
            url: '/pages/ucenter/evaluate/evaluate?id='+id
        })
    },
    // 选择分享框关闭
    hideDialog: function (e) {
        let that = this;
        that.setData({
            showShareDialog: false,
        });
    },
    // 弹出分享选择弹出层 判断是否登录
    shareTo: function () {
        let userInfo = wx.getStorageSync('userInfo');
        if (userInfo == '') {
            util.loginNow();
            return false;
        } else {
            this.setData({
                showShareDialog: !this.data.showShareDialog,
            });
        }
    },
    // 跳转海报分享界面
    createShareImage: function () {
        let id = this.data.id;
        wx.navigateTo({
            url: '/pages/share/index?goodsid=' + id
        })
    },
    // 当点击图片预览 图片停在该滑块的index下
    bindchange: function (e) {
        let current = e.detail.current;
        this.setData({
            current: current
        })
    },
    // 点击该输入框输入商品数量
    inputNumber(event) {
        let number = event.detail.value;
        this.setData({
            number: number
        });
    },
    // 配置分享
    onShareAppMessage: function (res) {
        let id = this.data.id;
        let name = this.data.goods.productName;
        let image = this.data.goods.titleImg;
        return {
            title: name,
            path: '/pages/goods/goods?id=' + id,
            imageUrl: image
        }
    },
    // 获取商品详情
    getGoodsInfo: function () {
        let that = this;
        util.requestApi(api.getProductInfo, {
            productID: that.data.id
        }).then(function (res) {
            if (res.code == 200) {
                let goods = res.content
                let skuList = res.content.sku;
                for (let i = 0; i < skuList.length; i++) {
                    if (skuList[i].param.length > 0) {
                        for (let j = 0; j < skuList[i].param.length; j++) {
                            skuList[i].param[j].checked = false
                        }
                    }
                }
                goods.sku = skuList;
                that.setData({
                    // 商品详情
                    goods: goods,
                    // 商品库存
                    goodsNumber: res.content.inventory,
                    gallery: res.content.media,
                    // 结束加载动画
                    loading: 1
                })
                WxParse.wxParse('goodsDetail', 'html', res.content.content, that);
            }

        })
    },
    // 选择规格
    clickSkuValue: function (event) {
        let index = event.currentTarget.dataset.index;
        let parentIndex = event.currentTarget.dataset.parentIndex;
        let goods = this.data.goods;
        for (let i = 0; i < goods.sku.length; i++) {
            if (i == parentIndex) {
                for (let j = 0; j < goods.sku[i].param.length; j++) {
                    if (j == index) {
                        if (goods.sku[i].param[j].checked) {
                            goods.sku[i].param[j].checked = false
                        } else {
                            goods.sku[i].param[j].checked = true
                        }
                    } else {
                        goods.sku[i].param[j].checked = false;
                    }
                }
            }
        }
        this.setData({
            goods: goods
        })
        // //重新计算spec改变后的信息
        this.changeSpecInfo();
        //重新计算哪些值不可以点击
    },
    //获取选中的规格信息
    getCheckedSpecValue: function () {
        let checkedValues = {
            skuID: [],
            skuPID: []
        };
        let checkedNameList = [];
        let specificationList = this.data.goods.sku;
        for (let i = 0; i < specificationList.length; i++) {
            for (let j = 0; j < specificationList[i].param.length; j++) {
                if (specificationList[i].param[j].checked) {
                    checkedValues.skuID.push(specificationList[i].param[j].id)
                    checkedValues.skuPID.push(specificationList[i].param[j].parentID)
                    checkedNameList.push(specificationList[i].param[j].name)
                }
            }
        }
        this.setData({
            checkedSkuProductName: checkedNameList.join('&')
        })
        return checkedValues;
    },
    // 点击选择规格商品数量重置回1和设置选择的商品信息
    changeSpecInfo: function () {
        // 拿到规格长度 判断下面选中的规格是否选择完整
        let skuListLength = this.data.goods.sku.length
        // 拿到sku对应查询列表
        let skuListInfo = this.data.goods.skuInfo
        // 拿到选中的值
        let checkedSkuID = this.getCheckedSpecValue();
        // 判断sku是否选择完整
        if (skuListLength === checkedSkuID.skuID.length && skuListLength === checkedSkuID.skuPID.length) {
            // 判断选择的规格
            for (let i = 0; i < skuListInfo.length; i++) {
                if (skuListInfo[i].skuID.toString() === checkedSkuID.skuID.toString() && skuListInfo[i].skuPID.toString() === checkedSkuID.skuPID.toString()) {
                    // 有该规格的商品 展示该规格商品信息
                    this.setData({
                        checkedSkuProductInfo: skuListInfo[i],
                        skuPriceVisible: true
                    })
                }
            }
        } else {
            this.setData({
                skuPriceVisible: false
            })
        }
    },
    // 监听界面隐藏后取消轮播图的自动滚动功能
    onHide: function () {
        this.setData({
            autoplay: false
        })
    },
    // 获取购物车数量
    getCartCount: function () {
        let that = this;
        let userID = wx.getStorageSync('userID')
        util.requestApi(api.getUserCartCount, {
            userID: userID
        }).then(function (res) {
            if (res.code === 200) {
                that.setData({
                    cartGoodsCount: res.content
                });
            }

        });
    },
    // 下拉刷新
    onPullDownRefresh: function () {
        wx.showNavigationBarLoading()
        this.getGoodsInfo();
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
    },
    // 点击进入购物车界面
    openCartPage: function () {
        wx.switchTab({
            url: '/pages/cart/cart',
        });
    },
    // 点击跳转至主界面
    goIndexPage: function () {
        wx.switchTab({
            url: '/pages/index/index',
        });
    },
    // 点击规格数量选择框弹出
    switchAttrPop: function () {
        if (this.data.openAttr == false) {
            this.setData({
                openAttr: !this.data.openAttr
            });
        }
    },
    // 点击服务信息框弹出
    switchServePop: function () {
        if (this.data.openServe == false) {
            this.setData({
                openServe: !this.data.openServe
            });
        }
    },
    // 点击关闭数量选择商品规格选择弹出框
    closeAttr: function () {
        this.setData({
            openAttr: false,
        });
    },
    // 点击关闭服务信息弹出框
    closeServe: function () {
        this.setData({
            openServe: false,
        });
    },
    // 加入购物车
    addToCart: function () {
        // 判断是否登录，如果没有登录，则登录
        util.loginNow();
        var that = this;
        let userInfo = wx.getStorageSync('userInfo');
        if (userInfo == '') {
            return false;
        }
        if (that.data.openAttr == false) {
            //打开规格选择窗口
            that.setData({
                openAttr: !that.data.openAttr
            });
        } else {
            // 暂停单人购买功能 return结束该函数
            // that.setData({
            //     BuyRemindShow:true
            // });
            // return;
            // 判断商品是否需要选择规格
            if (this.data.goods.sku.length > 0) {
                if (!this.data.skuPriceVisible) {
                    wx.showToast({
                        image: '/images/icon/icon_error.png',
                        title: '请选择规格',
                    });
                    return false;
                }
                // 验证库存
                if (this.data.checkedSkuProductInfo.stock < this.data.number) {
                    //要买的数量比库存多
                    wx.showToast({
                        image: '/images/icon/icon_error.png',
                        title: '库存不足',
                    });
                    return false;
                }
                let userID = wx.getStorageSync('userID')
                util.requestApi(api.addShoppingCart, {
                    productID: that.data.goods.productID,
                    count: that.data.number,
                    skuPID: that.data.checkedSkuProductInfo.skuPID,
                    skuID: that.data.checkedSkuProductInfo.skuID,
                    middleID: that.data.checkedSkuProductInfo.middleID,
                    userID: userID
                }).then(function (res) {
                    if (res.code == 200) {
                        that.setData({
                            openAttr: false,
                        });
                        wx.showToast({
                            title: '添加成功',
                        });
                        that.getCartCount()
                    }
                })
            } else {
                // 验证库存
                if (this.data.goods.inventory < this.data.number) {
                    //要买的数量比库存多
                    wx.showToast({
                        image: '/images/icon/icon_error.png',
                        title: '库存不足',
                    });
                    return false;
                }
                let userID = wx.getStorageSync('userID')
                util.requestApi(api.addShoppingCart, {
                    productID: that.data.goods.productID,
                    count: that.data.number,
                    skuPID: null,
                    skuID: null,
                    middleID: null,
                    userID: userID
                }).then(function (res) {
                    if (res.code == 200) {
                        that.setData({
                            openAttr: false,
                        });
                        wx.showToast({
                            title: '添加成功',
                        });
                        that.getCartCount()
                    }
                })
            }
        }
    },
    // 点击购买
    fastToCart: function () {
        // 判断是否登录，如果没有登录，则登录
        util.loginNow();
        let userInfo = wx.getStorageSync('userInfo');
        if (userInfo == '') {
            return false;
        }
        var that = this;
        if (this.data.openAttr === false) {
            //打开规格选择窗口
            this.setData({
                openAttr: !this.data.openAttr
            });
        } else {
            // 暂停单人购买功能 return结束该函数
            // that.setData({
            //     BuyRemindShow:true
            // });
            // return;
            // 支付功能
            // 判断当前产品是否需要选择规格
            if (this.data.goods.sku.length > 0) {
                // 商品需要选择规格
                // 判断规格是否选择完整
                if (!this.data.skuPriceVisible) {
                    wx.showToast({
                        image: '/images/icon/icon_error.png',
                        title: '请选择规格',
                    });
                    return false;
                }
                // 验证库存
                if (this.data.checkedSkuProductInfo.stock < this.data.number) {
                    //要买的数量比库存多
                    wx.showToast({
                        image: '/images/icon/icon_error.png',
                        title: '库存不足',
                    });
                    return false;
                }
                // 设置选中的商品信息
                app.selectGoods = [{
                    checkedGoods: this.data.goods,
                    goodsNumber: this.data.number,
                    skuHave: true,
                    checkedSkuProductInfo: this.data.checkedSkuProductInfo
                }]
                // 跳转至确认商品信息页面
                wx.navigateTo({
                    url: '/pages/order-check/index'
                });
            } else {
                // 商品不需要选择规格

                // 验证库存
                if (this.data.goods.inventory < this.data.number) {
                    //要买的数量比库存多
                    wx.showToast({
                        image: '/images/icon/icon_error.png',
                        title: '库存不足',
                    });
                    return false;
                }
                // 设置选中的商品信息
                app.selectGoods = [{
                    checkedGoods: this.data.goods,
                    goodsNumber: this.data.number,
                    skuHave: false,
                }]
                // 跳转至确认商品信息页面
                wx.navigateTo({
                    url: '/pages/order-check/index'
                });
            }
        }
    },
    // 点击减少商品数量
    cutNumber: function () {
        this.setData({
            number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
        });
        this.setData({
            disabled: ''
        });
    },
    // 点击增加商品数量
    addNumber: function () {
        this.setData({
            number: Number(this.data.number) + 1
        });
        let check_number = this.data.number + 1;
        if (this.data.goods.inventory < check_number) {
            this.setData({
                disabled: true
            });
        }
    },
    // 得到评论列表
    getComment(){
        let that=this;
        util.requestApi(api.getComment,{
            productID:that.data.id,
            size:10,
            page:1,
        }).then((res)=>{
            if(res.code==200){
                that.setData({
                    commentNum:res.content.count,
                    comment:res.content.data[0]
                });
            }
        })
    }
})